#include "msgparse.h"



MsgParse::MsgParse(QObject *parent) : QObject(parent)
{
    stat = MSG_IDEL;
}
void MsgParse::setIdel(void)
{
    stat = MSG_IDEL;
}
uint8_t MsgParse::parsing(uint8_t data)
{
    uint8_t rq=0;
    static uint16_t msgIndex,checkSum;
    static PACKAGE_t package;

    switch(++stat)
    {
            case MSG_HEAD:
            {
                    //qDebug()<<"MSG_HEAD："<<data;
                    if(data==HEAD)
                    {
                            package.head = data;
                            package.len = 0;
                            package.payload.clear();
                            checkSum = 0;
                            msgIndex = 0;
                    }
                    else    stat = MSG_IDEL;
                    break;
            }
            case MSG_MSGTYPE:
            {
                    //qDebug()<<"MSG_MSGTYPE:"<<msg.type;
                    package.type = data;
                    checkSum += data;
                    break;
            }
            case MSG_LEN:
            {
                    //qDebug("MSG_LEN");
                    checkSum += data;
                    if((data>>8 & 0x01)==0x01 && package.len==0){
                        package.len = (data & 0x7f)*128;
                        stat = MSG_MSGTYPE;
                    }else{
                        package.len = package.len+data;
                        if(package.len==0)   // 没有消息内容
                        {
                            stat = MSG_PAYLOAD;
                        }
                    }
                    break;
            }
            case MSG_PAYLOAD:
            {
                    package.payload.append(data);
                    checkSum += data;
                    msgIndex++;
                    if(package.len==msgIndex)      stat = MSG_PAYLOAD;
                    else                           stat = MSG_LEN;
                    break;
            }
            case MSG_CKH:
            {
                    //qDebug("MSG_CKH");
                    package.ckH = data;
                    break;
            }
            case MSG_CKL:
            {
                    package.ckL = data;
                    //qDebug()<<checkSum<<"  "<<msg.ckH<<" "<<msg.ckL;
                    if(((checkSum>>8) & 0x00ff)== package.ckH && (checkSum & 0x00ff)== package.ckL)
                    {
                           rq = 1; // 校验成功
                           parsingOk(package.type,package.len,package.payload,package.ckH,package.ckL);
                    }
                    else {
                           rq = 0;  // 校验失败
                    }
                    stat = MSG_IDEL;
                    break;
            }
            default:
            {
                    stat = MSG_IDEL;
                    break;
            }
    }
    return rq;
}
